<?php

namespace App\Controller;
use Think\Controller;

/**
 * [积分商城]
 * @author Legend. <xcx_legender@qq.com>
 * @param
 * @return
 */
class MallController extends UserBaseController {
	const LogPager = 5; // 记录的分页条数

	static $text_map = [
		'type' => ['exchange' => '兑换', 'gamble' => '抽奖'],
		'entity' => ['virtual' => '虚拟', 'real' => '实物'],
	];

	var $testUids = [55, 54, 53, 3425, 86, 49, 76, 3473, 97, 3530];

	// 积分商城首页
	// modify by liubo<liubo@ilongyuan.com.cn> at 2016-06-07
	public function index() {
		$appToken = $this->user['appToken'];
		$this->assign('appToken',$appToken);
		// return $this->display('Mall/await');
		$this->display();
	}

	public function static_web() {
		return $this->display('Mall/await');
		$this->display('static');
	}

	// 展示兑换信息
	public function show($id = 0) {
		$gift = event('Gift')->detail($id);
		if (!$gift) {
			return $this->showError('商品信息错误!');
		}
		$appToken = $this->user['appToken'];
		$this->assign('appToken',$appToken);
		$this->assign('gift', $gift);
		$this->assign('user', $this->user);
		$this->display();
	}

	// 兑换记录
	public function log() {
		$list = $this->getLogList(0);
		$this->assign('list', $list);
		$this->assign('score',$this->user['score']);
		$this->display();
	}

	// 获取兑换记录
	protected function getLogList($p = 1) {
		$map = [
			'uid' => (int) $this->user['id'],
			'object_type' => 'gift',
		];
		if (empty($p)) {
			$codes = service('Codes')->where($map)->order('bindtime desc')->select();
		} else {
			$codes = service('Codes')->where($map)->order('bindtime desc')->limit(10)->page($p)->select();
		}
		$gift_ids = $codes ? array_column($codes, 'object_id') : [];
		$gifts = service('Gift')->where(['id' => ['in', $gift_ids]])->select();
		$gifts = array_column($gifts, null, 'id');
		foreach ($codes as &$value) {
			$value['gift'] = $gifts[$value['object_id']];
		}
		return $codes;
	}

	// 积分记录
	public function score_log() {
		$p = I('p', 1, 'intval');
		$p = $p > 0 ? $p : 1;
		$list = $this->getScorelogList($p);
		$this->assign('_list', $list);
		if (IS_AJAX) {
			$ret = [];
			$ret['count'] = count($list);
			$ret['html'] = $this->fetch('block_score_log_list');
			return $this->ajaxReturn($ret);
		} else {
			$this->assign('user', $this->user);
			$this->display();
		}
	}

	// 获取积分记录
	protected function getScorelogList($p = 1) {
		$map = [
			'uid' => (int) $this->user['id'],
		];
		$list = service('ScoreLog')->where($map)->order('create_time desc')->limit(10)->page($p)->select();
		return $list;
	}

}